﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SPHelper
{
	public class Event
	{
		/// <summary>
		/// Get list of SPList items that were recently added or changed
		/// list is not sorted!
		/// </summary>
		/// <param name="web"></param>
		/// <param name="listsToInclude"></param>
		/// <param name="listsToExclude"></param>
		/// <param name="itemMinimumDate"></param>
		/// <returns></returns>
		public static List<SPListItem> GetUpcomingEvents(SPList list, bool isIncludeItemsStartedButNotEndedYet)
		{
			string currentEventListUrl = null;
			string currentItemUrl = null;
			List<SPListItem> items = null;
			try
			{
				// init
				if (list == null) { throw new Exception("SPListItem passed is null"); }
				items = new List<SPListItem>();
				currentEventListUrl = list.DefaultViewUrl;


				// get list items
				foreach (SPListItem item in list.Items)
				{
					currentItemUrl = item.Url;
					if (isIncludeItem(item, isIncludeItemsStartedButNotEndedYet)) { items.Add(item); }
					currentItemUrl = null;
				}

				// get list folders
				if (list.Folders != null)
				{
					foreach (SPListItem folder in list.Folders)
					{
						currentItemUrl = folder.Url;
						if (isIncludeItem(folder, isIncludeItemsStartedButNotEndedYet)) { items.Add(folder); }
						currentItemUrl = null;
					}
				}
			}
			catch (Exception ex)
			{
				SPHelper.Log.WriteError("r6ey7yfdhtddrssGsrdrtyfud", ex,
					"current list: " + currentEventListUrl + ", current item: " + currentItemUrl);
				items = null;
			}
			return items;
		}


		/// <summary>
		/// Get all upcoming events from all event/task type lists
		/// </summary>
		/// <param name="web"></param>
		/// <param name="isIncludeItemsStartedButNotEndedYet"></param>
		/// <param name="isIncludeTaskLists"></param>
		/// <returns></returns>
		public static List<SPListItem> GetUpcomingEvents(SPWeb web, bool isIncludeItemsStartedButNotEndedYet, bool isIncludeTaskLists)
		{
			List<SPListItem> items = null;
			try
			{
				// init
				if (web == null) { throw new Exception("SPWeb passed is null"); }
				items = new List<SPListItem>();

				foreach (SPList list in web.Lists)
				{
					// determine if include this list
					bool isIncludeList = false;
					if (list.BaseTemplate == SPListTemplateType.Events) 
					{ 
						isIncludeList = true; 
					}
					else if (isIncludeTaskLists &&
						(list.BaseTemplate == SPListTemplateType.Tasks ||
						list.BaseTemplate == SPListTemplateType.GanttTasks ||
						list.BaseTemplate == SPListTemplateType.IssueTracking)
						)
					{
						isIncludeList = true;
					}

					// if include list, call original
					if (isIncludeList)
					{
						List<SPListItem> _items = GetUpcomingEvents(list, isIncludeItemsStartedButNotEndedYet);
						if (_items != null && _items.Count > 0) { items.AddRange(_items); }
					}
				}
			}
			catch (Exception ex)
			{
				SPHelper.Log.WriteError("fxgjcjyftdrr", ex);
				items = null;
			}
			return items;
		}

		private static bool isIncludeItem(SPListItem item, bool isIncludeItemsStartedButNotEndedYet)
		{
			bool _isIncludeItem = false;
			if (item != null)
			{
				string contentTypeName = SPHelper.ContentType.GetContentTypeName(item);
				if (!string.IsNullOrEmpty(contentTypeName))
				{
					DateTime? startDate = null;
					DateTime? endDate = null;
					DateTime? devNull = null;
					GetDatesFromItem(item, ref startDate, ref endDate, ref devNull);

					// date filter
					_isIncludeItem = false;
					if (startDate != null)
					{
						if (startDate.Value.Date >= DateTime.Now.Date)
						{
							if (endDate != null && endDate.Value.Date == DateTime.Now.Date && endDate.Value.AddHours(1) < DateTime.Now)
							{
								// the meeting is today, but has been over for over an hour
								_isIncludeItem = false;
							}
							else
							{
								// item's start date is today or later
								_isIncludeItem = true;
							}
						}
						else if (isIncludeItemsStartedButNotEndedYet && endDate != null && endDate.Value.Date >= DateTime.Now.Date)
						{
							// item has already started, but has not yet ended
							_isIncludeItem = true;
						}
					}
					else if (endDate != null && endDate.Value.Date >= DateTime.Now.Date)
					{
						// only end date defined (such as a due date) and it is today or later
						_isIncludeItem = true;
					}
				}
			}
			return _isIncludeItem;
		}


		/// <summary>
		/// Get's item date if of a certain content type, such as event, task, issue, etc.
		/// </summary>
		/// <param name="item"></param>
		/// <param name="startDate"></param>
		/// <param name="endDate"></param>
		/// <param name="date"></param>
		public static void GetDatesFromItem(SPListItem item, ref DateTime? startDate, ref DateTime? endDate, ref DateTime? date)
		{
			// init
			startDate = null;
			endDate = null;
			date = null;

			if (item != null)
			{
				string contentTypeName = SPHelper.ContentType.GetContentTypeName(item);
				if (!string.IsNullOrEmpty(contentTypeName))
				{
					if (contentTypeName == "Event")
					{
						try
						{
							startDate = item["EventDate"] as DateTime?;
							endDate = item["EndDate"] as DateTime?;
						}
						catch { }
					}
					else if (contentTypeName == "Task" || contentTypeName == "Project Task")
					{
						try
						{
							startDate = item["StartDate"] as DateTime?;
							endDate = item["DueDate"] as DateTime?;
						}
						catch { }
					}
					else if (contentTypeName == "Issue")
					{
						try
						{
							endDate = item["DueDate"] as DateTime?;
						}
						catch { }
					}
				}

				// determine overall date
				if (startDate != null) { date = startDate; }
				else if (endDate != null) { date = endDate; }
			}
		}
	}
}
